<?php

namespace App\WeChat\Message;

use App\Model\AutoReplyModel;
use App\Model\MpInActivitySubscribeUserModel;
use App\Model\UserModel;
use App\WeChat\Message\Activity\Activity;
use App\WeChat\WeChatUtil;
use EasySwoole\WeChat\Bean\OfficialAccount\Message\News;
use EasySwoole\WeChat\Bean\OfficialAccount\Message\NewsItem;
use EasySwoole\WeChat\Bean\OfficialAccount\RequestMsg;

class OnMessageSubscribe
{
    public static function handle(RequestMsg $msg)
    {
        $weChatUtil = new WeChatUtil();
        $accessToken = $weChatUtil->getAccessToken();
        //1.第一条文字回复
        $weChatUtil->sendTextMsg($msg->getFromUserName(), self::text(), $accessToken);
        //2.设置用户关注状态
        sgo(function () use ($msg) {
            $userModel = new UserModel();
            $userModel->setSubscribeStatus($msg->getFromUserName(), true);
        });
        self::addSubscribeFlag($msg);
        //3.第二条链接消息回复
        return self::news($msg, $weChatUtil, $accessToken);
    }

    //公众号领书活动期间关注的用户记录状态到数据库
    private static function addSubscribeFlag(RequestMsg $msg)
    {
        sgo(function () use ($msg) {
            if (Activity::isActivity()) {
                $nickname = (new WeChatUtil())->brzComGetUnionIdByOpenid((new WeChatUtil())->getAccessToken(), $msg->getFromUserName(), 'nickname');
                (new MpInActivitySubscribeUserModel())->add($msg->getFromUserName(), MpInActivitySubscribeUserModel::flagSubscribe, $nickname);
            }
        });
    }

    //关注后文字回复
    static function text(): string
    {
        $autoReply = new AutoReplyModel();
        return $autoReply->getReply(AutoReplyModel::TYPE_SUBSCRIBE);
    }

    private static function news(RequestMsg $msg, WeChatUtil $weChatUtil, string $accessToken): News
    {
        $news = new News();
        $news->setFromUserName($msg->getFromUserName());
        $news->setToUserName($msg->getToUserName());
        $newsItem = new NewsItem();
        $nickname = $weChatUtil->brzComGetUnionIdByOpenid($accessToken, $msg->getFromUserName(), 'nickname');
        $newsItem->setTitle("{$nickname}，我们已经开通了家长专属直播间，点击进入>");
        $newsItem->setDescription("家长好好学习，孩子天天向上");
        $newsItem->setPicUrl('https://mini.dongjinyu.com/mobile/icon/si.jpg');
        $newsItem->setUrl('https://mini.dongjinyu.com/wechat/main');
        $news->push($newsItem);
        return $news;
    }
}